package com.hht.tools.uilib

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.hht.baselibs.dialog.BaseDialog
import com.hht.baselibs.dialog.CommonDialog
import com.hht.baselibs.util.ViewUtils
import com.hht.toolanduilibs.showLog
import com.hht.toolanduilibs.startActivityExt
import com.hht.toolanduilibs.util.FileUtils
import com.hht.toolanduilibs.util.usbcamera.CameraManagerUtils
import com.hht.toolanduilibs.wb.WhiteBoardHelp.Companion.getInstall
import com.hht.tools.R
import com.hht.wblib.WhiteBoardHelp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

class ToolsAndUiLibsUI : AppCompatActivity(),
    CameraManagerUtils.OnPreviewResultCallBack, CoroutineScope by MainScope() {
    private lateinit var mCameraIv: ImageView
    private lateinit var mPictureIv: ImageView
    private lateinit var mOpenBt: Button
    private lateinit var mTakeBt: Button
    private lateinit var annotationBt: Button
    private lateinit var whiteBoardBt: Button
    private lateinit var mContext: Context

    private lateinit var mCameraManagerUtils: CameraManagerUtils
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = this
        setContentView(R.layout.activity_tools_and_ui_libs_ui)
        mCameraManagerUtils = CameraManagerUtils(this)
        mCameraManagerUtils.setOnPreviewResultCallBack(this)
        initView()
        checkAndRequestPermission()
    }

    @SuppressLint("NewApi")
    private fun initView() {
        mCameraIv = findViewById(R.id.camera_iv)
        mPictureIv = findViewById(R.id.picture_iv)
        mOpenBt = findViewById(R.id.open_bt)
        mTakeBt = findViewById(R.id.take_bt)
        annotationBt = findViewById(R.id.annotation_bt)
        whiteBoardBt = findViewById(R.id.white_board_bt)
        mOpenBt.setOnClickListener {
            mCameraManagerUtils.switchCamera()
        }

        mTakeBt.setOnClickListener {
            mCameraManagerUtils.setTakePicture(true)
        }
        annotationBt.setOnClickListener {
            if (!Environment.isExternalStorageManager()) {
                showSettingsDialog()
            } else {
                val annotation = WhiteBoardHelp.getInstance(this).openAnnotation()
                "annotation==$annotation".showLog()
            }
        }

        whiteBoardBt.setOnClickListener {
            if (!Environment.isExternalStorageManager()) {
                showSettingsDialog()
            } else {
                val whiteboard = WhiteBoardHelp.getInstance(this).openWhiteBoard()
                "whiteboard==$whiteboard".showLog()
            }
        }
    }

    override fun onPreviewResult(bitmap: Bitmap) {
        launch {
            mCameraIv.setImageBitmap(bitmap)
        }
    }

    override fun onResume() {
        super.onResume()
        mCameraManagerUtils.onResume()

    }


    override fun onPause() {
        mCameraManagerUtils.onPause()
        super.onPause()
    }

    @SuppressLint("NewApi")
    override fun onTakePicture(bitmap: Bitmap) {
        launch {
            mPictureIv.setImageBitmap(bitmap)
            val bean = FileUtils.saveFile(bitmap, "Tools", context = mContext)
            if (bean.saveFileSuccess) {
                if (!Environment.isExternalStorageManager()) {
                    showSettingsDialog()
                } else {
                    val picToWb = WhiteBoardHelp.getInstance(mContext).sendPicturesToWhiteBoard(bean.file)
                    "picToWb==$picToWb".showLog()
                }
            }
        }
    }

    private fun checkAndRequestPermission() {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
        ) {
            // 权限未被授予，请求权限
            ActivityCompat.requestPermissions(this,
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.SYSTEM_ALERT_WINDOW,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE),
                112)
        }
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            112 -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //同意
                } else {
                    //拒绝
                    finish()
                }
            }
        }
    }

    private fun showSettingsDialog() {
        CommonDialog.newInstance()
            .setLayoutId(R.layout.settings_dialog_layout)
            .setConVertListener(object : CommonDialog.ViewConvertListener {
                override fun convertView(holder: ViewUtils, dialog: BaseDialog) {
                    dialog.setSize(1300, 700)
                    dialog.setOutCancel(false)
                    holder.setOnClickListener(R.id.settings_cancel_dialog) {
                        dialog.dismiss()
                    }
                    holder.setOnClickListener(R.id.settings_ok_dialog) {
                        dialog.dismiss()
                        mContext.startActivityExt {
                            action = Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
                            data = Uri.parse("package:${mContext.packageName}")
                        }
                    }
                }

            }).showDialog(supportFragmentManager, "settingsDialog")
    }
}